<template>
  <div class="permission-container">
    <div class="app-container">
      <el-card class="card-header">
        <div style="text-align: right; margin-bottom: 20px">
          <el-button type="primary" size="small" @click="addPerBtnFn(1,'0')">添加权限</el-button>
        </div>
      </el-card>
      <!-- 表格 -->
      <el-card class="card">
        <el-table border :data="permissionList" row-key="id">
          <el-table-column label="名称" prop="name" />
          <el-table-column label="标识" prop="code" />
          <el-table-column label="描述" prop="description" />
          <el-table-column label="操作">
            <template v-slot="{row}">
              <el-button v-if="row.type===1" type="text" @click="addPerBtnFn(2,row.id)">添加</el-button>
              <el-button type="text" @click="editFn(row.id)">编辑</el-button>
              <el-button type="text" @click="delFn(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <!-- 添加的弹窗 -->
      <per-dialog ref="perDialog" :all-permission-list="allPermissionList" />
    </div>
  </div>
</template>

<script>
import { getPermissionListAPI, getPermissionDetailAPI, delPermissionAPI } from '@/api'
import { transTree } from '@/utils'
import PerDialog from './components/perDialog.vue'
export default {
  name: 'Permission',
  components: {
    PerDialog
  },
  data() {
    return {
      permissionList: [], // 权限管理树形列表数据
      allPermissionList: [] // 权限管理扁平列表数据
    }
  },
  created() {
    this.getPermissionList()
  },
  methods: {
    // 获取权限列表
    async getPermissionList() {
      // 发送请求
      const res = await getPermissionListAPI()
      if (!res.success) return this.$message.error(res.message)
      // 存放扁平的数据
      this.allPermissionList = res.data
      // 将数据及逆行树形化并保存
      this.permissionList = transTree(res.data, '0')
    },
    // 添加权限事件
    // 接受俩个参数，参数一：新增数据的type值；参数二：父级id值
    addPerBtnFn(type, pid) {
      // 添加事件进入 isEdi=false
      this.$refs.perDialog.isEdi = false
      // 添加type值
      this.$refs.perDialog.formData.type = type
      // 添加数据的父级ID值
      this.$refs.perDialog.formData.pid = pid
      // 弹窗关闭
      this.$refs.perDialog.showDialog = true
    },
    // 编辑事件函数
    async editFn(id) {
      // 编辑事件进入，isEdi=true
      this.$refs.perDialog.isEdi = true
      const res = await getPermissionDetailAPI(id)
      // 数据回显
      this.$refs.perDialog.formData = res.data
      // 弹窗弹出
      this.$refs.perDialog.showDialog = true
    },
    async delFn(id) {
      const res = await delPermissionAPI(id)
      // 删除失败
      if (!res.success) this.$message.error(res.message)
      // 删除成功提示
      this.$message.success(res.message)
      // 重新获取数据
      this.getPermissionList()
    }
  }
}
</script>

<style lang="scss" scoped>

.card{
  margin-top: 15px;
}
</style>
